﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;
public partial class monthTicketAction : System.Web.UI.Page
{    
    //Inject log4net
    private static readonly ILog logger = LogManager.GetLogger(typeof(monthTicketAction).Name);
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                object id = this.Context.Items["id"];
                if (id != null)
                {
                    hdnId.Value = id.ToString();
                }

                object command = this.Context.Items["CommandName"];
                if (command != null)
                {
                    hdnCommand.Value = command.ToString();
                }
                LoadDDL();
                Inits();
            }
            lblErrorPlat.Visible = false;
            lblFromErr.Visible = false;
            lblEndDateErr.Visible = false;
            lblMsg.Visible = false;
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
            lblMsg.Visible = true;
        }
    }

    private void Inits()
    {
        try
        {
            btnReset.ImageUrl = "images/xoa.gif";
            btnReset.Attributes.Add("onmouseover", "this.src='images/xoa_hover.gif'");
            btnReset.Attributes.Add("onmouseout", "this.src='images/xoa.gif'");
            btnCancel.ImageUrl = "images/huy.gif";
            btnCancel.Attributes.Add("onmouseover", "this.src='images/huy_hover.gif'");
            btnCancel.Attributes.Add("onmouseout", "this.src='images/huy.gif'");
            trPrice.Visible = true;
            switch (hdnCommand.Value.ToUpper())
            {
                case "EDITTICKET":
                    LoadEditTicket();
                    break;
                case "EXTEND":
                    LoadExtendTicket();
                    break;
                default:
                    LoadSellTicket();
                    break;
            }            
        }
        catch (Exception)
        {
            throw;
        }
       
        
    }

    private void LoadDDL() {
        IList<PlateType> listType = new PlateType().GetAll();
        ddlTypeCar.DataSource = listType;
        ddlTypeCar.DataTextField = "Name";
        ddlTypeCar.DataValueField = "ID";
        ddlTypeCar.DataBind();

        IList<CarColor> listColor = new CarColor().GetAll();
        ddlColor.DataSource = listColor;
        ddlColor.DataTextField = "Name";
        ddlColor.DataValueField = "ID";
        ddlColor.DataBind();

        IList<ParkingFloor> listFloor = new ParkingFloor().GetAll();
        ddlFloor.DataSource = listFloor;
        ddlFloor.DataTextField = "Name";
        ddlFloor.DataValueField = "ID";
        ddlFloor.DataBind();
    }

    private void Save()
    {
        if (Session["Employee"] == null)
        {
            return;
        }
        MonthCard month = new MonthCard();
        if (String.IsNullOrEmpty(hdnCommand.Value))
        {
            return;
        }

        if (hdnCommand.Value.ToUpper().Equals("EXTEND")||
            hdnCommand.Value.ToUpper().Equals("EDITTICKET"))
        {
            month = month.GetById(new Guid(hdnId.Value));
        }

        if (month == null)
        {
            return;
        }         
               
        DateTime fromDate = DateTime.Now;
        DateTime toDate = DateTime.Now;
        if (!Utils.IsDate(txtFromDate.Text, out fromDate)||
            !Utils.IsDate(txtEndDate.Text, out toDate))
        {
            lblMsg.Text = "Sai định dạng ngày/tháng/năm";
            return;
        }
        month.FromDate = fromDate;
        month.ToDate = toDate;
        month.Price=Int32.Parse(txtPrice.Text);
        if (Session["Employee"] != null)
        {
            Employee emp = (Employee)Session["Employee"];
            month.LastUser = emp;
        }
        else
        {
            return;
        }
        switch (hdnCommand.Value.ToUpper())
        {
            case "EXTEND":
                month.Renew(month);
                break;
            case "EDITTICKET":
                month.PlateNumber = txtPlat.Text;
                month.PlateType = new PlateType();
                month.PlateType.ID = SqlHelper.CheckIntNull(ddlTypeCar.SelectedValue);

                month.CarColor = new CarColor();
                if (ddlColor.SelectedIndex > 0)
                {
                    month.CarColor.ID = new Guid(ddlColor.SelectedValue);
                }
                else
                {
                    month.CarColor.ID = Guid.Empty;
                }
                

                month.ParkingFloor = new ParkingFloor();
                if (ddlFloor.SelectedIndex > 0)
                {
                    month.ParkingFloor.ID = new Guid(ddlFloor.SelectedValue);
                }
                else
                {
                    month.ParkingFloor.ID = Guid.Empty;
                }                

                month.Update(month);
                break;
            default://insert
                month.ID = Guid.NewGuid();
                month.PlateNumber = txtPlat.Text;
                month.PlateType = new PlateType();
                month.PlateType.ID = SqlHelper.CheckIntNull(ddlTypeCar.SelectedValue);

                month.CarColor = new CarColor();
                if (ddlColor.SelectedIndex > 0)
                {
                    month.CarColor.ID = new Guid(ddlColor.SelectedValue);
                }
                else
                {
                    month.CarColor.ID = Guid.Empty;
                }


                month.ParkingFloor = new ParkingFloor();
                if (ddlFloor.SelectedIndex > 0)
                {
                    month.ParkingFloor.ID = new Guid(ddlFloor.SelectedValue);
                }
                else
                {
                    month.ParkingFloor.ID = Guid.Empty;
                }

                month.Customer = new Customer();
                month.Customer.CustomerID = new Guid(hdnId.Value);
                month.Insert(month);
                break;
        }
    }

    private void LoadCustomer()
    {
        Customer cust = new Customer();
        string id = hdnId.Value;
        cust = cust.GetById(new Guid(id));
        if (cust != null)
        {
            lblCode.Text = cust.CustomerCode;
            lblName.Text = cust.CustomerName;
            lblPhone.Text = cust.Phone;
            lblAddress.Text = cust.Address;
        }
    }

    private void LoadSellTicket()
    {
        LoadCustomer();
        tdTicketInfo.Visible = false;
        pnlMonthTicket.Visible = true;
        lblTitle.Text = "Thêm mới vé tháng";
        ltrTitleInfo.Text = "Thông tin bán vé tháng";
        btnSave.ImageUrl = "images/save.gif";
        btnSave.Attributes.Add("onmouseover", "this.src='images/save_hover.gif'");
        btnSave.Attributes.Add("onmouseout", "this.src='images/save.gif'");
        txtPlat.Text = String.Empty;
        ddlTypeCar.SelectedIndex = 0;
        ddlColor.SelectedIndex = 0;
        ddlFloor.SelectedIndex = 0;
        txtPrice.Text = String.Empty;
        DateTime fromDate = Utils.DBDate;
        if (fromDate.Day > 5)
        {
            fromDate = new DateTime(fromDate.Year, fromDate.Month+1, 5);
        }
        else
        {
            fromDate = new DateTime(fromDate.Year, fromDate.Month, 5);
        }
        DateTime toDate = fromDate.AddMonths(1);
        txtFromDate.Text = fromDate.ToString(Constants.DATE_PATTERN);
        txtEndDate.Text = toDate.ToString(Constants.DATE_PATTERN);
        txtPlat.Focus();
    }

    private void LoadEditTicket()
    {
        tdTicketInfo.Visible = false;
        pnlMonthTicket.Visible = true;
        btnSave.ImageUrl = "images/edit.jpg";
        btnSave.Attributes.Add("onmouseover", "this.src='images/edit_hover.jpg'");
        btnSave.Attributes.Add("onmouseout", "this.src='images/edit.jpg'");
        lblTitle.Text = "Chỉnh sửa vé tháng";
        ltrTitleInfo.Text = "Thông tin chỉnh sửa vé tháng";
        string id = hdnId.Value;
        if (string.IsNullOrEmpty(id))
        {
            return;
        }
        MonthCard month = new MonthCard();
        month = month.GetById(new Guid(id));
        if (month != null)
        {
            Customer cust = month.Customer;
            if (cust != null)
            {
                lblCode.Text = cust.CustomerCode;
                lblName.Text = cust.CustomerName;
                lblPhone.Text = cust.Phone;
                lblAddress.Text = cust.Address;
            }            
            ////////////////////////////////////////
            txtPlat.Text = month.PlateNumber;
            hdnPlate.Value = txtPlat.Text;
            lblPlate.Text = txtPlat.Text;
            ddlTypeCar.SelectedValue = month.PlateType.ID.ToString();
            if (month.PlateType.ID == 0)//free
            {
                trPrice.Visible = false;
            }
            lblType.Text = month.PlateType.GetName;
            
            if (!month.CarColor.ID.Equals(Guid.Empty))
            {
                ddlColor.SelectedValue = month.CarColor.ID.ToString();
                lblColor.Text = month.CarColor.GetName;
            }

            if (!month.ParkingFloor.ID.Equals(Guid.Empty))
            {
                ddlFloor.SelectedValue = month.ParkingFloor.ID.ToString();
                lblFloor.Text = month.ParkingFloor.GetName;
            }            
            txtFromDate.Text = month.FromDate.ToString(Constants.DATE_PATTERN);            
            txtEndDate.Text = month.ToDate.ToString(Constants.DATE_PATTERN);
            lblDate.Text = String.Format(" {0} đến {1}", txtFromDate.Text, txtEndDate.Text);
            txtPrice.Text = month.Price.ToString();
            txtPlat.Focus();
        }        
    }

    private void LoadExtendTicket()
    {
        tdTicketInfo.Visible = true;
        pnlMonthTicket.Visible = false;
        btnSave.ImageUrl = "images/extend.jpg";
        btnSave.Attributes.Add("onmouseover", "this.src='images/extend_hover.jpg'");
        btnSave.Attributes.Add("onmouseout", "this.src='images/extend.jpg'");
        lblTitle.Text = "Gia hạn vé tháng";
        ltrTitleInfo.Text = "Thông tin gia hạn vé tháng";
        //disable control;
        txtPlat.ReadOnly = true;
        txtPlat.CssClass = "disable width_200";

        string id = hdnId.Value;
        if (string.IsNullOrEmpty(id))
        {
            return;
        }
        MonthCard month = new MonthCard();
        month = month.GetById(new Guid(id));
        if (month != null)
        {
            Customer cust = month.Customer;
            if (cust != null)
            {
                lblCode.Text = cust.CustomerCode;
                lblName.Text = cust.CustomerName;
                lblPhone.Text = cust.Phone;
                lblAddress.Text = cust.Address;
            }
            ////////////////////////////////////////            
            hdnPlate.Value = month.PlateNumber;
            lblPlate.Text = hdnPlate.Value;
            lblType.Text = month.PlateType.GetName;

            if (!month.CarColor.ID.Equals(Guid.Empty))
            {
                lblColor.Text = month.CarColor.GetName;
            }

            if (!month.ParkingFloor.ID.Equals(Guid.Empty))
            {
                lblFloor.Text = month.ParkingFloor.GetName;
            }

            DateTime fromDate = month.FromDate;
            DateTime toDate = month.ToDate;
            DateTime dbDate = Utils.DBDate;

            if (toDate >= dbDate)
            {
                fromDate = toDate;
            }
            else
            {
                fromDate = dbDate;
            }

            toDate = fromDate.AddMonths(1).AddDays(5-fromDate.Day);

            txtFromDate.Text = fromDate.ToString(Constants.DATE_PATTERN);
            txtEndDate.Text = toDate.ToString(Constants.DATE_PATTERN);
            lblDate.Text = String.Format(" {0} đến {1}",
                            month.FromDate.ToString(Constants.DATE_PATTERN),
                            month.ToDate.ToString(Constants.DATE_PATTERN));
            txtPrice.Text = month.Price.ToString();
            if (month.PlateType.ID == 0)//free
            {
                trPrice.Visible = false;
            }
            txtFromDate.Focus();
        }
    }
   
    private bool CheckPlatIsValid()
    {
        bool flag = true;

        DateTime fromDate = DateTime.Now;
        if (!Utils.IsDate(txtFromDate.Text, out fromDate))
        {
            txtFromDate.Focus();
            lblFromErr.Text = "Sai định dạng ngày/tháng/năm";
            lblFromErr.Visible = true;
            flag = false;
        }
        DateTime toDate = DateTime.Now;
        if (!Utils.IsDate(txtEndDate.Text, out toDate))
        {
            txtEndDate.Focus();
            lblEndDateErr.Text = "Sai định dạng ngày/tháng/năm";
            lblEndDateErr.Visible = true;
            flag = false;
        }
        if (fromDate.ToString("yyyyMMdd").CompareTo(toDate.ToString("yyyyMMdd")) > 0)
        {
            txtFromDate.Focus();
            lblFromErr.Text = "Ngày bắt đầu phải nhỏ hơn hoặc bằng ngày kết thúc!";
            lblFromErr.Visible = true;
            flag = false;
        }
        Guid id = Guid.Empty;
        switch (hdnCommand.Value.ToUpper())
        {
            case "SELL":
                id = Guid.NewGuid();
                break;
            case "EDITTICKET":
                id = new Guid(hdnId.Value);
                break;
        }
        MonthCard month = new MonthCard();
        if (month.IsExistedPlateNumber(txtPlat.Text.Trim(),id))
        {
            txtPlat.Focus();
            lblErrorPlat.Visible = true;
            flag = false;
        }       
       
        return flag;
    }


    protected void btnSave_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            if (CheckPlatIsValid())
	        {
        		 Save();
                 Response.Redirect(Constants.CUSTOMER_SHOW + "?page=3", false);
	        }
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
            lblMsg.Visible = true;
        }
        
    }
    protected void btnReset_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            Inits();
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
            lblMsg.Visible = true;
        }
    }
    protected void btnCancel_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            Response.Redirect(Constants.CUSTOMER_SHOW + "?page=3", false);
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }

    protected void ddlTypeCar_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            trPrice.Visible = true;
            if (ddlTypeCar.SelectedIndex <= 0)
            {
                return;
            }
            int id = SqlHelper.CheckIntNull(ddlTypeCar.SelectedValue);
            if (id == 0) //free
            {
                txtPrice.Text = "0";
                trPrice.Visible = false;
            }
            else
            {
                if (ddlTypeCar.SelectedIndex > 0)
                {
                    PlateType plateType = new PlateType();
                    plateType = plateType.GetById(id);
                    txtPrice.Text = plateType.Price.ToString();
                }
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }
}
